from turbogears import widgets
import cherrypy

class Source(widgets.Resource):
    params = ["src"]

    def __init__(self, rel, src, *args, **kw):
        super(Source, self).__init__(*args, **kw)
        self.src = src
        self.rel = rel

    def __hash__(self):
        return hash((self.src, self.rel))

    def __eq__(self, other):
        return self.src == getattr(other, "src", None) and self.rel == getattr(other, 'rel', None)


class OpenIDMetadata(Source):
    template = """
        <link rel="${rel}" href="${src}" />
    """
    params_doc = {
        'rel': 'OpenID metadata type',
        'src': 'OpenID metadata target',
    }
    params = params_doc.keys()

    retrieve_css = widgets.set_with_self

class XRDSLocation(widgets.Source):
    template = """
        <meta http-equiv="X-XRDS-Location"
            content="${src}" />
    """
    params_doc = {
        'src': 'XRDS location',
    }
    params = params_doc.keys()

    retrieve_css = widgets.set_with_self


class OpenIDDelegationWidget(widgets.Widget):
    params_doc = {
        'openid_server': 'OpenID v1 server',
        'openid_delegate': 'OpenID v1 delegate',
        'openid2_local_id': 'OpenID v2 local id',
        'openid2_provider': 'OpenID v2 provider',
        'xrds_location': 'XRDS location',
    }
    params = params_doc.keys()

    def retrieve_css(self):
        headers = []
        if self.openid_server:
            headers.append(OpenIDMetadata(rel="openid.server", src=self.openid_server))
        if self.openid_delegate:
            headers.append(OpenIDMetadata(rel="openid.delegate", src=self.openid_delegate))
        if self.openid2_local_id:
            headers.append(OpenIDMetadata(rel="openid2.local_id", src=self.openid2_local_id))
        if self.openid2_provider:
            headers.append(OpenIDMetadata(rel="openid2.provider", src=self.openid2_provider))
        if self.xrds_location:
            headers.append(XRDSLocation(src=self.xrds_location))
        return headers
